package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.dto.MemberReservationDto;
import com.zzyl.nursing.vo.TimeCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 预约信息Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-04
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService
{
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询预约信息
     * 
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id)
    {
        return reservationMapper.selectById(id);
    }

    /**
     * 查询预约信息列表
     * 
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation)
    {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation)
    {

        return reservationMapper.insert(reservation);

    }

    /**
     * 修改预约信息
     * 
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation)
    {
        return reservationMapper.updateById(reservation);
    }

    /**
     * 批量删除预约信息
     * 
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids)
    {
        return reservationMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除预约信息信息
     * 
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id)
    {
        return reservationMapper.deleteById(id);
    }

    /**
     * 更新预约信息状态
     */
    @Override
    public void updateReservationStatus() {
        //1.查询状态为0待报道的预约状态，（预约状态，0：待上门，1：已完成，2：已取消，3：已过期）
        List<Reservation> list = list(Wrappers.<Reservation>lambdaQuery()
                .eq(Reservation::getStatus, 0)
                .le(Reservation::getTime, LocalDateTime.now()));
        //2.修改状态为3过期状态
        list.forEach(item -> {
            item.setStatus(3);
        });

        //批量更新
        updateBatchById(list);
    }

    /**
     * 分页查询预约信息
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public TableDataInfo selectPage(Integer pageNum, Integer pageSize, Integer status) {

        //获取登录用户id
        Long userId = UserThreadLocal.getUserId();
        if (ObjectUtil.isEmpty(userId)) {
            throw new BaseException("请先登录");
        }
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getCreateBy, userId)
                .eq(ObjectUtil.isNotEmpty(status), Reservation::getStatus, status)
                .orderByDesc(Reservation::getCreateTime);
        Page page = new Page<>(pageNum, pageSize);
        page = page(page, queryWrapper);
        return createTableDataInfo(page);
       /* // 构建查询条件
        QueryWrapper<Reservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(status != null && status >= 0, "status", status);
        IPage<Reservation> page = new Page<>(pageNum, pageSize);
        // 执行分页查询
        IPage<Reservation> resultPage = page(page, queryWrapper);
        return getTableDataInfo(resultPage);*/
    }

    /**
     * 封装分页信息
     * @param page
     * @return
     */
    private TableDataInfo createTableDataInfo(Page page) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("请求成功");

        return tableDataInfo;
    }


    /**
     * 添加预约信息
     *
     * @param memberReservationDto
     * @return
     */
    @Override
    public int add(MemberReservationDto memberReservationDto) {
        /*Reservation reservation = new Reservation();
        BeanUtils.copyProperties(memberReservationDto, reservation);
        // 双重保障：代码设置 + 自动填充
        if (reservation.getStatus() == null) {
            reservation.setStatus(0);
        }
        baseMapper.insert(reservation);

        return reservation;*/
        Long userId = UserThreadLocal.getUserId();
        Reservation reservation = BeanUtil.toBean(memberReservationDto, Reservation.class);
        reservation.setCreateBy(userId+"");
        reservation.setUpdateBy(userId+"");
        reservation.setStatus(0);

        return save(reservation) ? 1 : 0;
    }

    /**
     * 取消预约
     * @param id
     * @return
     */
    @Override
    public int cancelReservation(Long id) {
        //获取预约信息
        Reservation reservation = getById(id);
        //判断预约是否存在
        if (ObjectUtil.isEmpty(reservation)) {
            throw new BaseException("预约不存在");
        }
        //设置状态为2取消
        reservation.setStatus(2);
        //设置操作用户
        reservation.setUpdateBy(UserThreadLocal.getUserId() + "");

        return updateById(reservation) ? 1 : 0;
    }

    /**
     * 查询每个时间段剩余预约次数
     * @param time
     * @return
     */
    @Override
    public List<TimeCountVo> countByTime(Long time) {
        //  时间戳转LocalDateTime
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);
        // 获取当天的开始时间
        LocalDateTime startTime = localDateTime.toLocalDate().atStartOfDay();
        //获取当天的结束时间
        LocalDateTime endTime = startTime.plusDays(1);
        // 调用mapper,查询每个时间段剩余预约次数
        List<TimeCountVo> list = reservationMapper.countReservationForTime(startTime, endTime);

        return list;

    }

    /**
     * 获取取消的预约次数
     * @param userId
     * @return
     */
    @Override
    public int getCancelledCount(Long userId) {
        //获取当前起始时间
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);

        //构建查询构造器
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件 用户id，起始时间，结束时间
        queryWrapper.eq(Reservation::getUpdateBy, userId)
                .between(Reservation::getUpdateTime, startTime, endTime);
        //统计次数
        int count = (int) count(queryWrapper);
        return count;
    }
}
